import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Bug, BugFixResult } from '@/types/bug'

export const useBugStore = defineStore('bug', () => {
  const bugs = ref<Bug[]>([
    {
      id: '1',
      title: '登录功能异常',
      description: '用户登录时出现认证失败，无法正常登录系统',
      severity: 'high',
      status: 'pending',
      file: 'src/components/Login.vue',
      line: 45,
      createdAt: new Date('2024-01-15'),
      updatedAt: new Date('2024-01-15')
    },
    {
      id: '2',
      title: '数据加载缓慢',
      description: '首页数据加载时间过长，用户体验差',
      severity: 'medium',
      status: 'pending',
      file: 'src/services/api.ts',
      line: 23,
      createdAt: new Date('2024-01-14'),
      updatedAt: new Date('2024-01-14')
    },
    {
      id: '3',
      title: '表单验证失效',
      description: '用户注册表单的邮箱验证规则不生效',
      severity: 'critical',
      status: 'pending',
      file: 'src/components/Register.vue',
      line: 67,
      createdAt: new Date('2024-01-13'),
      updatedAt: new Date('2024-01-13')
    }
  ])

  const fixingBugId = ref<string | null>(null)

  const pendingBugs = computed(() => bugs.value.filter(bug => bug.status === 'pending'))
  const fixingBugs = computed(() => bugs.value.filter(bug => bug.status === 'fixing'))
  const fixedBugs = computed(() => bugs.value.filter(bug => bug.status === 'fixed'))

  const getBugById = (id: string) => bugs.value.find(bug => bug.id === id)

  const updateBugStatus = (id: string, status: Bug['status'], solution?: string, error?: string) => {
    const bug = getBugById(id)
    if (bug) {
      bug.status = status
      bug.updatedAt = new Date()
      if (solution) bug.solution = solution
      if (error) bug.error = error
    }
  }

  const addBug = (bug: Omit<Bug, 'id' | 'createdAt' | 'updatedAt'>) => {
    const newBug: Bug = {
      ...bug,
      id: Date.now().toString(),
      createdAt: new Date(),
      updatedAt: new Date()
    }
    bugs.value.push(newBug)
  }

  const setFixingBug = (id: string | null) => {
    fixingBugId.value = id
  }

  return {
    bugs,
    fixingBugId,
    pendingBugs,
    fixingBugs,
    fixedBugs,
    getBugById,
    updateBugStatus,
    addBug,
    setFixingBug
  }
})